package cn.itcast.controller;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController{

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

	@RequestMapping("/login")
	public String login(String email, String password, HttpServletRequest request,HttpSession session) {
//	    1、做非空判断 邮箱或密码都不能为空
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password) ){
            request.setAttribute("error","邮箱或密码不能为空");
            return "forward:/login.jsp" ; // 请求转发
        }

//        2、使用shiro方式登录（认证） 三个步骤：1、创建令牌 2、获取主题subject 3、开始认证
        String password_page = new Md5Hash(password,email,2).toString();
        UsernamePasswordToken token = new UsernamePasswordToken(email, password_page);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token); //AuthenticationToken
        } catch (AuthenticationException e) {
            e.printStackTrace();
            request.setAttribute("error","邮箱或密码错误");
            return "forward:/login.jsp" ; // 请求转发
        }

//        获取当前登录人
        User user = (User) subject.getPrincipal();

//  比较一致，登录成功后把用户放入到session中，
        session.setAttribute("loginUser",user); //loginUser 这个名字在页面中使用

//        获取当前登录人的菜单权限
        List<Module> moduleList  = moduleService.findModuleListByUser(user);

        session.setAttribute("modules",moduleList);

		return "home/main"; //跳转到首页面
	}

    //退出
    @RequestMapping(value = "/logout",name="用户登出")
    public String logout(HttpSession session){
        SecurityUtils.getSubject().logout();   //登出
//        session.removeAttribute("loginUser");  //自己session中的数据不需要自己手动清空了

        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home(){
	    return "home/home";
    }
}
